<?php
require_once __DIR__ . '/vendor/autoload.php';

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class Helper_liveroom_url {

    static function checkpush($acctid,$userid,$openid){

        $updatetag = false;
        $edu_video_teacher  = teacher::find('user_id = ?',$userid)->getOne();
        if(!$edu_video_teacher->id()){
             return array('code'=>0,'msg'=>'您还不是主播');
        }else{
//             $endtime = $edu_video_teacher->urladdtime + 20*3600;//加上86400---就是url截止有效期

//             if($endtime <= time()){//
//                 $updatetag = true;
//             }else{
//                 if(empty($edu_video_teacher->playurl) ||  empty($edu_video_teacher->sourceurl)){
//                     $updatetag = true;
//                 }else{
//                     return array('code'=>0,'msg'=>$edu_video_teacher->urladdtime.'添加，未到有效期');
//                 }
               
//             }
     
        }
        
  
      
        if(1){
           
             $acct = Acct::find('id = ?',$acctid)->getOne();
             if(!$acct->id()){
                 return array('code'=>1,'msg'=>'请求参数acctid错误');
             }
              if(empty($acct->playdomain) ||empty($acct->pushdomain)  ||empty($acct->pushauthkey))//4个配置有一个是空的
              {
                  
                  return array('code'=>1,'msg'=>'请先填写推流配置');
              }
            
             //准备参数
            $appname = 'xianrenzhang';
            $streamname = $acctid.$openid.date('ymd');
            $streamname = $acctid.$openid;
            $pushdomain = trim($acct->pushdomain);
            $playdomain = trim($acct->playdomain);
            $sourceurl = "rtmp://{$pushdomain}/{$appname}/{$streamname}";
            $playurl = "rtmp://{$playdomain}/{$appname}/{$streamname}";
            //只要确保推流鉴权就是安全的
            //URI-Timestamp-rand-uid-PrivateKey
            $endtime = time()+60*24*60;
            //$endtime = 1576741429;
            $uri = "/{$appname}/{$streamname}";
            $signstr = sprintf('%s-%d-0-0-%s',$uri,$endtime,$acct->pushauthkey);
          //  echo $signstr;echo '<br>';
            $sign = md5($signstr);
            
     //       var_dump($sign);die;
           // $sourceurl .= "?auth_key={$endtime}-0-0-{$sign}";
            $edu_video_teacher->appname = 'xianrenzhang';
            $edu_video_teacher->streamname = $streamname;
            $edu_video_teacher->sourceurl = $sourceurl;
            $edu_video_teacher->urladdtime = time();
            $edu_video_teacher->playurl = $playurl;
            $edu_video_teacher->appname = $appname;
            

            // $res = self::tovod($acctid,$openid);
            // var_dump($res);die;
            // if($res['code']==0){
            //     $edu_video_teacher->vodurl="";

            // }
            $edu_video_teacher->save();
            return array('code'=>0,'msg'=>'ok');


        }
    }
    //禁止流
    static function prohibit($acctid,$openid)
    {
        $updatetag = true;
        $edu_video_teacher  = teacher::find('openid = ?',$openid)->getOne();

        if(!$edu_video_teacher->id()){
            $updatetag = false;
        }else{
            $endtime = $edu_video_teacher->urladdtime+6*86400;//加上6*86400---就是url截止有效期
            if($endtime >= time()){//不是7天---6天
                $updatetag = false;
            }else{
                return array('code'=>0,'msg'=>$edu_video_teacher->urladdtime.'有效期已到');
            }

        }
        if(!$updatetag) {
            $acct = Acct::find('id = ?', $acctid)->getOne();
            if (!$acct->id()) {
                return array('code' => 1, 'msg' => '请求参数acctid错误');
            }
            if ( empty($acct->playdomain) || empty($acct->pushdomain) || empty($acct->aliaccessid) || empty($acct->aliaccesskey))//4个配置有一个是空的
            {
                return array('code' => 1, 'msg' => '配置不正确');
            }
            AlibabaCloud::accessKeyClient($acct->aliaccessid, $acct->aliaccesskey)
                ->regionId('cn-hangzhou')
                ->asDefaultClient();
            try {
                $result = AlibabaCloud::rpc()
                    ->product('live')
                    // ->scheme('https') // https | http
                    ->version('2016-11-01')
                    ->action('ForbidLiveStream')
                    ->method('POST')
                    ->host('live.aliyuncs.com')
                    ->options([
                        'query' => [
                        'RegionId' => "cn-shenzhen",
                        'AppName' => 'xianrenzhang',
                        'StreamName' => $acctid.$openid,//生成一个唯一的 acctid+openid
                        'LiveStreamType' => 'publisher', //用于指定主播推流还是客户端拉流，目前支持 “publisher”(主播推送)。
                        'DomainName' => $acct->playdomain,//播放、拉流域名
                        ],
                    ])
                    ->request();
                $res = $result->toArray();
                return array('code'=>0,'msg'=>$res);
            } catch (ClientException $e) {
                $res = $e->getErrorMessage();
                return array('code'=>1,'msg'=>$res);
            } catch (ServerException $e) {
                $res = $e->getErrorMessage();
                return array('code'=>1,'msg'=>$res);
            }
        }
    }
        //恢复流
    static function recovery($acctid,$openid){
        $updatetag = false;
        $edu_video_teacher  = teacher::find('openid = ?',$openid)->getOne();

        if(!$edu_video_teacher->id()){
            $updatetag = true;
        }else{
            $endtime = $edu_video_teacher->urladdtime+6*86400;//加上6*86400---就是url截止有效期
            if($endtime >= time()){//不是7天---6天
                $updatetag = true;
            }else{
                return array('code'=>0,'msg'=>$edu_video_teacher->urladdtime.'有效期已到');
            }
        }
        if($updatetag) {
            $acct = Acct::find('id = ?', $acctid)->getOne();
            if (!$acct->id()) {
                return array('code' => 1, 'msg' => '请求参数acctid错误');
            }
            if (empty($acct->playdomain) || empty($acct->pushdomain) || empty($acct->aliaccessid) || empty($acct->aliaccesskey))//5个配置有一个是空的
            {
                return array('code' => 1, 'msg' => '配置不正确');
            }
            AlibabaCloud::accessKeyClient($acct->aliaccessid, $acct->aliaccesskey)
                ->regionId('cn-hangzhou')
                ->asDefaultClient();

            try {
                $result = AlibabaCloud::rpc()
                    ->product('live')
                    // ->scheme('https') // https | http
                    ->version('2016-11-01')
                    ->action('ResumeLiveStream')
                    ->method('POST')
                    ->host('live.aliyuncs.com')
                    ->options([
                        'query' => [
                            'RegionId' => "cn-hangzhou",
                            'AppName' => 'xianrenzhang',
                            'StreamName' => $acctid.$openid,//生成一个唯一的 acctid+openid
                            'LiveStreamType' => 'publisher', //用于指定主播推流还是客户端拉流，目前支持 “publisher”(主播推送)。
                            'DomainName' => $acct->playdomain,//播放、拉流域名
                        ],
                    ])
                    ->request();
                $res = $result->toArray();
                return array('code'=>0,'msg'=>$res);
            } catch (ClientException $e) {
                $res = $e->getErrorMessage();
                return array('code'=>1,'msg'=>$res);
            } catch (ServerException $e) {
                $res = $e->getErrorMessage();
                return array('code'=>1,'msg'=>$res);
            }
        }
    }
    /**
     * 录制直播
     * @Author   xy
     * @DateTime 2020-02-17T11:22:52+0800
     * @param    [type]                   $acctid [description]
     * @param    [type]                   $openid [description]
     * @return   [type]                           [description]
     */
    static function tovod($acctid,$openid){
        // $liver =
        $acct = Acct::find('id = ?', $acctid)->getOne();
        if (!$acct->id()) {
            return array('code' => 1, 'msg' => '请求参数acctid错误');
        }
        if (empty($acct->playdomain) || empty($acct->pushdomain) || empty($acct->aliaccessid) || empty($acct->aliaccesskey))//5个配置有一个是空的
        {
            return array('code' => 1, 'msg' => '配置不正确');
        }
        $parm = "Action=AddLiveRecordVodConfig&AppName=xianrenzhang&DomainName={$acct->playdomain}&VodTranscodeGroupId=e2d796d3bb5fd8049d32bff62f940711";
        
        $utc_time = gmdate("Y-m-d\TH:i:s\Z");
        $none_str = Helper_common::get_rand_str(32,false);
        $uri = "AccessKeyId={$acct->aliaccessid}&Action=AddLiveRecordVodConfig&AppName=xianrenzhang&DomainName={$acct->playdomain}&Format=JSON&SignatureMethod=HMAC-SHA1&SignatureNonce={$none_str}&SignatureVersion=1.0&Timestamp={$utc_time}&Version=2016-11-01&VodTranscodeGroupId=e2d796d3bb5fd8049d32bff62f940711";
        $uri_encode = urlencode($uri);
        $uri_encode = str_replace(['+', '*'], ['%20', '%2A'], $uri_encode);
        $uri_encode = preg_replace('/%7E/', '~', $uri_encode);
        $uri_encode = 'GET&%2F&'.$uri_encode;
        var_dump($uri_encode);
        $url = "https://live.aliyuncs.com/?$uri";
        // var_dump($url);
        // $sign = urlencode($url);
        $str = $acct->aliaccesskey.'&';
        $hmac = hash_hmac("sha1", $uri_encode, $str,true);
        var_dump($hmac);
        $sign = base64_encode($hmac);
        var_dump($sign);
        $sign = urlencode($sign);
        $sign = str_replace(['+', '*'], ['%20', '%2A'], $sign);
        $sign = preg_replace('/%7E/', '~', $sign);
        $url = $url."&Signature=$sign";
        var_dump($url);
        $res = Helper_common::get_data($url);
        return $res;
        // var_dump()
        // AlibabaCloud::accessKeyClient($acct->aliaccessid, $acct->aliaccesskey)
        //     ->regionId('cn-beijing')
        //     ->asDefaultClient();

        try {
            $result = AlibabaCloud::rpc()
                ->product('live')
                ->scheme('https') // https | http
                ->version('2016-11-01')
                ->action('AddLiveRecordVodConfig')
                ->method('GET')
                ->host('live.aliyuncs.com')
                ->options([
                    'query' => [
                        // 'RegionId' => "cn-beijing",
                        'AppName' => 'xianrenzhang',
                        'VodTranscodeGroupId' => 'e2d796d3bb5fd8049d32bff62f940711',
                        // 'StorageLocation' => $acct->playdomain,
                        'StreamName' => $acctid.$openid,//生成一个唯一的 acctid+openid
                        //'LiveStreamType' => 'publisher', //用于指定主播推流还是客户端拉流，目前支持 “publisher”(主播推送)。
                        'DomainName' => $acct->playdomain,//播放、拉流域名
                    ],
                ])
                ->request();
            $res = $result->toArray();
            return array('code'=>0,'msg'=>$res);
        } catch (ClientException $e) {
            $res = $e->getErrorMessage();
            return array('code'=>1,'msg'=>$res);
        } catch (ServerException $e) {
            $res = $e->getErrorMessage();
            return array('code'=>1,'msg'=>$res);
        }
        
    }

}
